<?php
namespace app\common\controller;

use \app\check\controller\Check;
use app\common\lib\AliOss;

class Avatar extends Check
{
    private $img_max_size;

    /**
     * 上传图片
     * @return [type] [description]
     */
    public function upload($path = 'uploads')
    {
        $file = request()->file('avatar');

        if(isset($file))
        {
            $config = ['size'=>$this->img_max_size,'ext'=>'jpg,png,gif'];

            // tp5 文件上传验证
            $info        = $file->validate($config)->oss($path);
            if(!$info){
                return show(config('code.error'), $file->getError());
            }
            // 获取文件名
            $filename = $info->get_filename();

            $filename_start_index = strripos($filename,'/');
            $path = substr($filename,0,$filename_start_index);

            $filename_re = substr($filename,$filename_start_index);
//            return data=>
//            "path": "/uploads/20171024/",
//            "filename": "e849cc0b3a3b7a8620a9ad4a0959edbc.png"

            $file_path = DS . $path;

            if ($info) {
                $result = [
                    'code' => 200,
                    'data'   => [
                        'path'=> $file_path,
                        'filename'=>$filename_re,
                    ],
                    'msg'=>'ok'
                ];
            } else {
                $result = [
                    'code' => 10034,
                    'msg'=>$file->getError()
                ];
            }
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());

            try
            {
                (AliOss::getInstance())->ossUpload($filename,$content);
            }
            catch(OssException $e)
            {
                $result = [
                    'code' => 10034,
                    'msg'=>$e->getMessage()
                ];
            }

            return json($result);
        }
        else
        {
            return json(['code'=>10033,'msg'=>'File is not exited.']);
        }
    }

    /**
     * 批量上传图片
     * @param string $path
     * @return \think\response\Json [type] [description]
     */
    public function uploads($path = 'uploads')
    {
        if(empty($_FILES))  return json(['code'=>10033,'msg'=>'File is not exited.']);
        $files = [];
        foreach ($_FILES as $k => $f)
        {
            $temp = request()->file($k);
            $config = ['size'=>$this->img_max_size,'ext'=>'jpg,png,gif'];
//            $path = 'picture'.DS.$dir;
            // tp5 文件上传验证
            $info        = $temp->validate($config)->oss($path);
            // 获取文件名
            $filename = $info->get_filename();

            if (!$info) {
                $result = [
                    'code' => 10034,
                    'msg'=>$temp->getError()
                ];
            }
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());
            try{
                $this->ossClient->putObject($this->bucket, $filename, $content);
            } catch(OssException $e) {
                $result = [
                    'code' => 10034,
                    'msg'=>$e->getMessage()
                ];
            }
            if(isset($result['code']) && $result['code'] != 200) return json($result);

//            $filename = str_replace('upload','uploads',$filename);

            $files[] = DS.$filename;
        }
        return json(['code'=>10034,'data'=>$files,'msg'=>'Success']);
    }

    /**
     * 批量上传图片
     * @return [type] [description]
     */
    public function uploads_array($path = 'uploads')
    {
        if(empty($_FILES))  return ['imgs'=>[],'error'=>[]];
        $files = [];
        foreach ($_FILES as $k => $f)
        {
            $temp = request()->file($k);
            $config = ['size'=>$this->img_max_size,'ext'=>'jpg,png,gif'];
//            $path = 'picture'.DS.$dir;
            // tp5 文件上传验证
            $info        = $temp->validate($config)->oss($path);
            // 获取文件名
            $filename = $info->get_filename();

            if (!$info) {
                $files['error'][] = $temp->getError();
            }
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());
            try{
                $this->ossClient->putObject($this->bucket, $filename, $content);
            } catch(OssException $e) {
                $result = [
                    'code' => 10034,
                    'msg'=>$e->getMessage()
                ];
            }
            if(isset($result['code']) && $result['code'] != 200) return json($result);

//            $filename = str_replace('upload','uploads',$filename);

            $files['imgs'][] = DS . $filename;
        }
        return $files;
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function upload111($path = 'uploads')
    {
        $config = [
            'size' => 1024*1024*10,
            'ext'  => 'jpg,gif,png,bmp,jpeg'
        ];

        $file = $this->request->file('file');

        // tp5 文件上传验证
        $info        = $file->validate($config)->oss($path);
        // 获取文件名
        $filename = $info->get_filename();

        if ($info)
        {
            $result = [
                'error' => 0,
                'url'   => DS . $filename
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }
        // 字符串方式上传图片
        $content = file_get_contents($info->get_tmpname());

        try
        {
            $this->ossClient->putObject($this->bucket, $filename, $content);
        }
        catch(OssException $e)
        {
            $result = [
                'error'   => 1,
                'message' => $e->getMessage()
            ];
        }

        return json($result);
    }

    /**
     * 获取一个OssClient实例
     * @return null|OssClient
     */
    protected static function getInstance()
    {
        if (!(self::$_instance instanceof OssClient))
        {
            try
            {
                self::$_instance = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
            }
            catch (OssException $e)
            {
                printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
                printf($e->getMessage() . "\n");
                return null;
            }
        }
        return self::$_instance;
    }
    /**
     * 获取bucket
     * @return string
     */
    protected static function getBucketName()
    {
        return self::bucket;
    }
}
